package me.keiwu.admin.util;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Created by kei on 02/11/2017.
 */
public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);


    public static boolean uploadFile(MultipartFile file, String saveDir, String saveName) {
        return uploadFile(file, saveDir, saveName, null, null);
    }

    public static boolean uploadFile(MultipartFile file, String saveDir, String saveName, Integer width, Integer height) {
        File mDir = new File(saveDir);
        if (!mDir.exists() && !mDir.mkdirs()) return false;
        try {
            String path = mDir.getAbsolutePath();
            path = path.endsWith("/") ? path : path + "/";
            File saveFile =  new File(path + saveName);
            file.transferTo(saveFile);
            if (width != null && height != null) {
                Thumbnails.of(saveFile).size(width, height).toFile(saveFile);
            }
            return true;
        } catch (Exception e) {
            logger.error("error when uploadFile: ", e);
            return false;
        }
    }

}
